<template>
    <view class="app-container">

        <!-- 表单内容 -->
        <view class="form-container">
            <!-- Logo上传区域 -->
            <view class="form-item">
                <view class="form-label">商家Logo</view>
                <view class="logo-upload" @click="chooseLogo">
                    <image v-if="merchantInfo.logo && !tempFilePath" :src="merchantInfo.logo" class="logo-preview"
                        mode="aspectFill">
                    </image>
                    <image v-else-if="tempFilePath" :src="tempFilePath" class="logo-preview" mode="aspectFill">
                    </image>
                    <view v-else class="logo-placeholder">
                        <text class="upload-icon">📷</text>
                        <text class="upload-text">点击上传Logo</text>
                    </view>
                </view>
            </view>

            <!-- 商家名称 -->
            <view class="form-item">
                <view class="form-label">商家名称</view>
                <input v-model="merchantInfo.name" class="form-input" placeholder="请输入商家名称" maxlength="20" />
            </view>

            <!-- 联系电话 -->
            <view class="form-item">
                <view class="form-label">联系电话</view>
                <input v-model="merchantInfo.phone" class="form-input" placeholder="请输入联系电话" type="number"
                    maxlength="11" />
            </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-container">
            <button class="save-btn" @click="saveMerchantInfo" :disabled="!isFormValid">
                保存
            </button>
        </view>
    </view>
</template>

<script>
import { request } from '@/utils/request.js';
export default {

    data() {
        return {
            merchantInfo: {},
            merchantId: 0,
            tempFilePath: '',
            originalLogo: ''
        };
    },
    computed: {
        isFormValid() {
            return this.merchantInfo.name.trim() && this.merchantInfo.phone.trim();
        }
    },
    onLoad(props) {
        console.log('商户信息编辑页', props);
        this.merchantId = props.id || 0;
        this.getMerchantInfo();
    },
    methods: {
        // 获取商户信息
        async getMerchantInfo() {
            try {
                this.merchantInfo = uni.getStorageSync('companyInfo');
                console.log('商户信息', this.merchantInfo);
            } catch (error) {
                console.error('获取商户信息失败:', error);
            }
        },
        // 选择Logo
        async chooseLogo() {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    this.tempFilePath = res.tempFilePaths[0];
                },
                fail: (error) => {
                    console.error('选择图片失败:', error);
                    uni.showToast({
                        title: '选择图片失败',
                        icon: 'none'
                    });
                }
            });
        },
        // 保存商户信息
        async saveMerchantInfo() {
            if (!this.isFormValid) {
                uni.showToast({
                    title: '请填写完整信息',
                    icon: 'none'
                });
                return;
            }

            // 验证手机号格式
            if (!this.validatePhone(this.merchantInfo.phone)) {
                uni.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                });
                return;
            }

            try {
                uni.showLoading({
                    title: '保存中...'
                });

                // 如果有新选择的图片，则先上传图片
                if (this.tempFilePath) {
                    // 使用 Promise 包装上传操作，确保等待上传完成
                    await new Promise((resolve, reject) => {
                        uni.uploadFile({
                            url: 'https://abc.qctrips.cn/local-file/upload',
                            filePath: this.tempFilePath,
                            name: 'file',
                            header: {
                                'Authorization': uni.getStorageSync('accessToken') || ''
                            },
                            success: (uploadRes) => {
                                console.log('原始返回：', uploadRes);

                                let parsedData;
                                try {
                                    parsedData = JSON.parse(uploadRes.data);
                                } catch (err) {
                                    console.error('后端返回的不是合法 JSON：', uploadRes.data);
                                    uni.showToast({
                                        title: '返回数据格式错误',
                                        icon: 'none'
                                    });
                                    reject(err);
                                    return;
                                }
                                this.merchantInfo.logo = parsedData.data.url;
                                this.tempFilePath = ''; // 清除临时路径
                                resolve(parsedData);
                            },
                            fail: (error) => {
                                reject(error);
                            }
                        });
                    });
                }

                // 保存商户信息
                const res = await request({
                    url: `/merchant/update`,
                    method: 'PUT',
                    data: this.merchantInfo
                });

                if (res.code === 200) {
                    uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                    });
                    uni.setStorageSync('companyInfo', this.merchantInfo);
                    // 延迟返回上一页
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 1500);
                }
            } catch (error) {
                uni.hideLoading();
                console.error('保存失败:', error);
                uni.showToast({
                    title: '保存失败，请重试',
                    icon: 'none'
                });
            }
        },

        // 验证手机号
        validatePhone(phone) {
            const phoneReg = /^1[3-9]\d{9}$/;
            return phoneReg.test(phone);
        },

        // 返回上一页
        goBack() {
            uni.navigateBack();
        }
    },
};
</script>

<style scoped>
.app-container {
    min-height: 100vh;
    background-color: #f8f9fa;
}

/* 顶部导航 */
.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 32rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
    position: sticky;
    top: 0;
    z-index: 100;
}

.header-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-icon {
    font-size: 48rpx;
    color: #333;
    font-weight: bold;
}

.header-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.header-right {
    width: 60rpx;
}

/* 表单容器 */
.form-container {
    padding: 32rpx;
}

.form-item {
    margin-bottom: 48rpx;
}

.form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    font-weight: 500;
}

/* Logo上传 */
.logo-upload {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ddd;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    position: relative;
    overflow: hidden;
}

.logo-preview {
    width: 100%;
    height: 100%;
    border-radius: 14rpx;
}

.logo-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
}

.upload-icon {
    font-size: 48rpx;
    margin-bottom: 8rpx;
}

.upload-text {
    font-size: 24rpx;
}

/* 输入框 */
.form-input {
    width: 100%;
    height: 88rpx;
    background-color: #fff;
    border: 1rpx solid #e0e0e0;
    border-radius: 12rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
}

.form-input:focus {
    border-color: #007aff;
}

/* 保存按钮 */
.save-container {
    padding: 32rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-top: 1rpx solid #eee;
}

.save-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #007aff, #0056cc);
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
}

.save-btn:disabled {
    background: #ccc;
    color: #999;
}

.save-btn:active {
    opacity: 0.8;
}
</style>